from prg.common.common_base import CommonBase
import struct


class UdpData:
    def __init__(self, bytes_array=None):
        self.byte_array = bytes_array
        self.name = None
        self.number = None
        self.byte_data = None
        # if bytes_array is not None:
        #     self.recv_data()

    def get_bytes(self, encryption=None):
        head_bytes = struct.pack(">bii", int(self.name), len(self.byte_data), self.number)
        if not CommonBase.is_none_empty(encryption):
            self.byte_data = CommonBase.xor_encryption(key=encryption, data=self.byte_data)
        return head_bytes + self.byte_data

    def bind(self, encryption=None):
        read_byte_tmp = self.read_socket_data(9)
        name, data_len, number = struct.unpack(">bii", read_byte_tmp)
        self.name = name
        self.number = number
        self.byte_data = self.read_socket_data(data_len)
        if not CommonBase.is_none_empty(encryption):
            self.byte_data = CommonBase.xor_decrypt(key=encryption, data=self.byte_data)

    def read_socket_data(self, size):
        return self.byte_array.read(size)


